package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.ArticleFeign;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.exception.CustomException;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.builder.ArticleDtoBuilder;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
   @Autowired
   private WmNewsMapper wmNewsMapper;

   @Autowired
   private GreenTextScan greenTextScan;

   @Autowired
   private GreenImageScan greenImageScan;

   @Autowired
   private FileStorageService fileStorageService;

   @Autowired
   private WmUserMapper wmUserMapper;

   @Autowired
   private WmChannelMapper wmChannelMapper;

   @Autowired
   private ArticleFeign articleFeign;

   @Autowired
   private WmSensitiveMapper sensitiveMapper;

   @Autowired
   private Tess4jClient tess4jClient;

    /**
     * 自媒体文章审核
     *
     * @param articleId 自媒体文章id
     */
    @Override
    @Async
    @GlobalTransactional
    public void autoScanWmNews(Integer articleId) throws Exception {
        //1. 根据文章的id查询文章数据
        WmNews wmNews = wmNewsMapper.selectById(articleId);

        //2. 判断文章是否被删除 如果被删除则抛出异常
        if(null == wmNews){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        // 只有文章的状态位待审核的时候才需要走自动审核
        if(wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            //3. 从文章中 解析得到文章的文本类容和图片内容
            Map<String, Object> data = handleTextAndImages(wmNews);

            //4.1 自定义敏感词的审核'
            Boolean flag = handleSensitiveScan(data.get("text").toString(), wmNews);
            if(!flag){
                return;
            }

            //4. 把文本内容上传到阿里云进行审核 审核失败直接返回 成功则继续审核
            flag = handleTextScan(data.get("text").toString(), wmNews);
            if(!flag){
                return;
            }

            //5. 把图片上传到阿里云进行审核 审核失败直接返回 成功则继续审核
            flag = handleImageScan((List<String>) data.get("images"), wmNews);
            if(!flag){
                return;
            }

            //6. 把自媒体的文章数据同步到app端
            ResponseResult responseResult = saveAppArticle(wmNews);
            if(!responseResult.getCode().equals(200)){
                throw new CustomException(AppHttpCodeEnum.TRANSF_DATA_FRAIL);
            }

            //7. 修改自媒体文章的状态位9
            wmNews.setArticleId(Long.parseLong(responseResult.getData().toString()));
            updateWmNews(wmNews, (short)9, "审核成功");
        }

    }

    /**
     * 自定义敏感词的审核
     * @param text
     * @param wmNews
     * @return
     */
    private Boolean handleSensitiveScan(String text, WmNews wmNews) {
        Boolean flag = Boolean.TRUE;
        //1. 查询所有的敏感词
        List<WmSensitive> wmSensitives = sensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> list = wmSensitives.stream().map(item -> item.getSensitives()).collect(Collectors.toList());
        //2. 初始化DFA的敏感词库
        SensitiveWordUtil.initMap(list);

        //3. 判断是否有敏感词 如果有则更新审核状态位2
        Map<String, Integer> map = SensitiveWordUtil.matchWords(text);
        if(null != map && map.size() > 0){
            updateWmNews(wmNews, (short)2, "文本中存在自定义敏感词：" + map);
            flag = Boolean.FALSE;
        }

        //4. 返回审核的结果
        return flag;
    }

    /**
     * 同步数据到文章微服务
     * @param wmNews
     * @return
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {
        /*ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews,dto);

        //文章的布局
        dto.setLayout(wmNews.getType());

        dto.setCreatedTime(new Date());

        //封装作者的信息
        if(null != wmNews.getUserId()){
            dto.setAuthorId(wmNews.getUserId().longValue());
            WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
            dto.setAuthorName(wmUser.getName());
        }

        //封装频道数据
        if(null != wmNews.getChannelId()){
            WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
            dto.setChannelName(wmChannel.getName());
        }

        //设置文章id
        if(wmNews.getArticleId() != null){
            dto.setId(wmNews.getArticleId());
        }*/

        ArticleDtoBuilder builder = new ArticleDtoBuilder(wmNews, wmUserMapper, wmChannelMapper);
        ArticleDto dto = builder
                .buildBeanCopy()
                .buildAuthor()
                .buildChannel()
                .buildBasic()
                .builder();

        ResponseResult responseResult = articleFeign.saveArticle(dto);

        return responseResult;
    }

    /**
     * 图片审核
     * @param images
     * @param wmNews
     * @return
     */
    private Boolean handleImageScan(List<String> images, WmNews wmNews) throws Exception {
        Boolean flag = Boolean.TRUE;
        if(null == images && images.size() == 0){
            return flag;
        }

        //对图片进行去重
        images = images.stream().distinct().collect(Collectors.toList());

        // 下载图片
        List<byte[]> imagesList = new ArrayList<>(images.size());
        for (String url : images) {
            byte[] bytes = fileStorageService.downLoadFile(url);

            //创建图片对象
            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
            BufferedImage image = ImageIO.read(inputStream);

            //识别图片中的文本
            String result = tess4jClient.doOCR(image);

            //自定义敏感词审核
            flag = handleSensitiveScan(result, wmNews);
            if(!flag){
                return flag;
            }

            imagesList.add(bytes);
        }

        Map map = greenImageScan.imageScan(imagesList);

        if(null != map){
            if(map.get("suggestion").equals("block")){
                flag = Boolean.FALSE;
                updateWmNews(wmNews, (short)2, "图片中存在违规的内容");
            }else if(map.get("suggestion").equals("review")){
                flag = Boolean.FALSE;
                updateWmNews(wmNews, (short)3, "图片中存在不确定的内容需要进行人工审核");
            }
        }else{
            flag = Boolean.FALSE;
        }

        return flag;
    }

    /**
     * 通过阿里云接口审核文本内容
     * @param text
     * @param wmNews
     * @return
     */
    private Boolean handleTextScan(String text, WmNews wmNews) throws Exception {
        Boolean flag = Boolean.TRUE;

        if(StringUtils.isEmpty(text)){
            return flag;
        }

        Map map = greenTextScan.greeTextScan(text);
        if(null != map){
            if(map.get("suggestion").equals("block")){
                flag = Boolean.FALSE;
                updateWmNews(wmNews, (short)2, "文本内存中存在违规的内容");
            }else if(map.get("suggestion").equals("review")){
                flag = Boolean.FALSE;
                updateWmNews(wmNews, (short)3, "文本内存中存在不确定的内容需要进行人工审核");
            }
        }

        return flag;
    }

    /**
     * 更新文章的审核状态和原因
     * @param wmNews
     * @param status
     * @param reson
     */
    private void updateWmNews(WmNews wmNews, short status, String reson) {
        wmNews.setStatus(status);
        wmNews.setReason(reson);

        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 从文章中出去得到所有的图片和文本内容 并封装到一个Map中返回
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        StringBuilder sb = new StringBuilder();
        List<String> images = new ArrayList<>();

        //处理文本的内容
        if(StringUtils.isNotEmpty(wmNews.getContent())){
            List<Map> list = JSON.parseArray(wmNews.getContent(), Map.class);
            for (Map map : list) {
                if("text".equals(map.get("type").toString())){
                    sb.append(map.get("value").toString());
                }else{
                    images.add(map.get("value").toString());
                }
            }
        }

        //处理封面
        if(StringUtils.isNotEmpty(wmNews.getImages())){
            images.addAll(Arrays.asList(wmNews.getImages().split(",")));
        }

        //处理标题中的内容
        sb.append("-").append(wmNews.getTitle());

        Map<String, Object> map = new HashMap<>();
        map.put("text", sb.toString());
        map.put("images", images);

        return map;
    }
}
